var app = getApp(),
  fetchApi = require("../../../utils/httpPost.js"),
  formatTime = require("../../../component/common.js")
import Toast from '../../../component/vant/toast/toast';
const format = rate => Math.min(Math.max(rate, 0), 100);
Page({

  /**
   * 页面的初始数据
   */
  data: {
    recordList: [],
    pageIndex: 1,
    pageSize: 10,
    currentTab: 0,
    tabType: [0, 2],
    isShowQrCode: false,
    qrCode: '',
    qrCodeRegMer:'',
    nickName: '',
    codeUrlbg:'https://img.sdyuedou.com/simple/image/inviteuserbg.jpg',//背景图片
    codeUrlbgMer:'https://img.sdyuedou.com/simple/image/invitemerbg.jpg',//背景图片
    canvas:null,
    ctx:null,
    qrCodeRight:-100,
    flag:false,
    faceUrl:null,
    inviteType:0,
    dpr:1,
    cashMoney:{},
    reg_new_user_remark:'',
    reg_new_mer_remark:'',
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.onHttpInitFeedRecord();
  },
  onHttpInitFeedRecord() {
    var that = this;
    fetchApi.httpPost('/farm/feed/invitation/list', {
      pageIndex: that.data.pageIndex,
      pageSize: that.data.pageSize,
    }, function (res) {
      console.log("邀请记录", res)
      if (res.data.code == 0) {
        that.data.qrCode = res.data.data.qrCode;
        that.data.nickName = res.data.data.nickName;

        that.data.reg_new_user_remark = res.data.data.reg_new_user_remark;
        that.data.reg_new_mer_remark = res.data.data.reg_new_mer_remark;
        
        if(res.data.data.cash_role.maxMoney > 0){
          console.log('res.data.data.role.maxMoney',res.data.data.cash_role.maxMoney)
          that.data.cashMoney = parseInt(res.data.data.cash_role.maxMoney);
          console.log('cashMoney',that.data.cashMoney)
        }

        that.setData({
          qrCode: res.data.data.qrCode,
          qrCodeRegMer:res.data.data.qrCodeRegMer,
          nickName: res.data.data.nickName,
          faceUrl:res.data.data.faceUrl
        })
        if(res.data.totalcount > 0){
          that.data.pageIndex = that.data.pageIndex + 1;
          var recordList = res.data.data.records;
          if (recordList.length > 0) {
            for (var index in recordList) {
              that.data.recordList.splice(that.data.recordList.length, 0, recordList[index]);
            }
            that.setData({
              hasData: true,
              recordList: that.data.recordList
            })
          }
        }
      }
      wx.stopPullDownRefresh() //停止下拉刷新
      wx.hideNavigationBarLoading() //完成停止加载
      that.setData({
        netWork: true,
        isLoading: false,
      })
    }, function () {
      that.setData({
        netWork: false,
        hasData: false,
        isLoading: false,
      })
    })
  },
  handleOpenQrCode(e) {
    var isLogin = app.getStorageSync("isLogin");

    if(isLogin == 0){
      wx.navigateTo({
        url: '/pages/login/index',
      })
    }else{
      console.log('handleOpenQrCode',e);
      var type = e.currentTarget.dataset.type;
      this.data.inviteType = parseInt(type);
      this.setData({
        isShowQrCode: true,
        flag: true,
      })

      this.setData({
        qrCodeRight:50
      })
      this.showQr();
    }
  },
  handleCloseQrCode(){
    this.setData({
      isShowQrCode: false,
      flag: false,
    })
    this.setData({
      qrCodeRight:-100
    })
  },
  onReady(){
    this.showQr()
  },
  showQr(){
    const query = wx.createSelectorQuery();
    query.select('#myCanvas')
    .fields({
      id: true,
      node: true,
      size: true
    })
    .exec(this.init.bind(this))
  },
  //init函数 通过 Canvas.getContext('2d') 接口可以获取 CanvasRenderingContext2D 对象，实现了 [HTML Canvas 2D Context](https://www.w3.org/TR/2dcontext/) 定义的属性、方法。
  init(res) {
    console.log('init--------',res)
    const canvas = res[0].node
    const ctx = canvas.getContext('2d')
    this.data.dpr = wx.getSystemInfoSync().pixelRatio;//获取屏幕的像素比  值为2
     //新接口需显示设置画布宽高； w*2 h*2
     canvas.width = 300;
     canvas.height = 500;
    //  console.log('dpr',dpr)
    //  ctx.scale(this.data.dpr, this.data.dpr); //缩放

     this.setData({
      canvas,
      ctx
    });
    //渲染bg图片和二维码还有文字，必须按照顺序来，先渲染背景，再渲染logo，最后渲染文字，如果顺序不统一，logo先渲染，就会导致背景图片加载不出来。
    //向画布载入图片的方法
    this.canvasDraw(ctx,canvas).then(res=>{
      console.log('1',res)
        // 向画布载入logo的方法
      return this.code(ctx)
    }).then(rrr=>{
      console.log('2',rrr)
      //图片头像渲染完成之后，渲染文字
      this.title(ctx)
    })
  },
  // 封面图  使用 pormise方法来输出 代码执行成功，返回一个成功标识出去
  canvasDraw(ctx,canvas) {
      var that  = this;
      that.data.ctx = ctx;
      that.data.canvas = canvas;
    return new Promise(res=>{
      console.log('canvasDraw',res)
      let img = that.data.canvas.createImage(); //创建img对象
      console.log('that.data.inviteType',that.data.inviteType)
      if(that.data.inviteType == 0){
        img.src = that.data.codeUrlbg;
      }else{
        img.src = that.data.codeUrlbgMer;
      }
      img.onload = () => {
        console.log(img.complete); //true
        that.data.ctx.drawImage(img, 0, 0,300, 500);
          setTimeout(() => {
            res(true)
          }, 100);
      };  
    })

},
  // 头像 使用 pormise方法来输出 代码执行成功，返回一个成功标识出去
  code(ctx) {
    this.data.ctx = ctx;
    var that = this;
    return new Promise(rrr=>{
      let code = that.data.canvas.createImage(); //创建img对象
      code.onload = () => {
        that.data.ctx.drawImage(code, 78,225, 145, 145);
      };
      if(that.data.inviteType == 0){
        code.src = that.data.qrCode;
      }else{
        code.src = that.data.qrCodeRegMer;
      }

      let faceCode = that.data.canvas.createImage(); //创建img对象
      faceCode.onload = () => {
        that.data.ctx.drawImage(faceCode, 70,186, 30, 30);
      };
      faceCode.src = that.data.faceUrl;
      setTimeout(() => { rrr(true)  }, 100);
    })
  },

//文字模块，不使用pormise，因为他是最后模块，所有不需要了
  title(ctx) {
      let text = this.data.nickName;
      ctx.font = 'normal bold 12px sans-serif';
      ctx.fillText(text, 115, 208, 120)
  },
  downloadQrCode() {
    // 保存到相册
    var that = this;
    console.log('保存canvasId',this.data.canvas._canvasId)
    wx.canvasToTempFilePath({     //将canvas生成图片
      canvas:that.data.canvas,
      x: 0,
      y: 0,
      width: 600,
      height: 995,
      destWidth: 600*2,     //截取canvas的宽度
      destHeight:995*2,   //截取canvas的高度
      success: function (res) {
        console.log('生成图片成功：',res)
        wx.saveImageToPhotosAlbum({  //保存图片到相册
          filePath: res.tempFilePath,
          success: function (res) {
            wx.showToast({
              title: "保存图片成功！",
              duration: 2000
            })
            that.setData({
              flag:false
            })
          }
        })
      },
      fail:function(res){
        console.log('保存图片报错',res)
        that.setData({
          flag:false
        })
      }
    },this)
  
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.data.pageIndex = 1
    this.setData({
      recordList:[],
    })
    this.onHttpInitFeedRecord();
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.onHttpInitFeedRecord();
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    var that = this;
    var user_id = app.getStorageSync("user_id");
    console.log("转发成功 user_id", user_id);
    that.setData({
      flag:false
    })
    var titleMsg = "";
    var pathUrl = "";
    if(this.data.inviteType == 1){
      titleMsg = that.data.reg_new_mer_remark;
      pathUrl = '/pagesMer/pages/register/index?ag_id='+user_id;
    } else {
      titleMsg = that.data.reg_new_user_remark;
      pathUrl = '/pages/home/home?ag_id=' + user_id;
    }

    return {
      title: titleMsg,
      path: pathUrl,
      // imageUrl:'https://img.sdyuedou.com/simple/image/fenxiang_3.jpg',
      success: function (res) {
        console.log(res, "转发成功")
        that.setData({
          flag:false
        })
      },
      fail: function (res) {
        console.log(res, "转发失败");
        that.setData({
          flag:false
        })
      }
    }
  },
  goAddQuestion(){
    wx.navigateTo({
      url: '/pages/feedback/feedback',
    })
  },
})